/*
 *    Copyright 2008-2009 The PoCo Team
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.asemantics.poco.converters;

import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import java.util.TimeZone;

import org.apache.commons.beanutils.converters.AbstractConverter;

/**
 * 
 * @author Simone Tripodi
 * @version $Id: TimeZoneConverter.java 241 2009-12-20 00:25:17Z simone.tripodi@gmail.com $
 */
@SuppressWarnings("unchecked")
public final class TimeZoneConverter extends AbstractConverter {

    /**
     * Default timezone, corresponds to <i>GMT</i>.
     */
    private static final String DEFAULT_TIMEZONE = "GMT";

    private final static SimpleDateFormat TIMEZONE_FORMAT = new SimpleDateFormat("Z");

    public TimeZoneConverter() {
        this(TimeZone.getDefault());
    }

    public TimeZoneConverter(Object defaultValue) {
        super(defaultValue);
    }

    @Override
    protected Object convertToType(Class type, Object value) throws Throwable {
        String s = value.toString();
        int hourSeparator = s.indexOf(':');
        if (hourSeparator != -1) {
            s = s.substring(0, hourSeparator)
                    + s.substring(hourSeparator + 1);
        }
        return TimeZone.getTimeZone(DEFAULT_TIMEZONE + s);
    }

    @Override
    protected String convertToString(Object value) throws Throwable {
        String s = TIMEZONE_FORMAT.format(new GregorianCalendar((TimeZone) value).getTime());
        return s.substring(0, 3) + ':' + s.substring(3);
    }

    @Override
    protected Class getDefaultType() {
        return TimeZone.class;
    }

}
